/*
 * @Author: xiaxia
 * @Description: 
 * @Date: 2024-06-19 17:04:35
 * @LastEditTime: 2024-06-25 15:09:44
 * @FilePath: \project\src\utils\request.ts
 */
import axios from "axios";
import {ElMessage} from 'element-plus'
import useUserStore from "@/store/modules/user";


let request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 基础路径/api
  timeout: 5000,// 超时时间
})

// 请求与拦截器
request.interceptors.request.use((config) =>{
  let userStore = useUserStore()
  if(userStore.token) config.headers.token = userStore.token
  return config
})

// 响应拦截器
request.interceptors.response.use(
  (response)=>{
    return response.data
  },
  (err) =>{
    if (err && err.response){
      // 处理http网络错误
      let message = ''
      let status = err.response.status
      switch(status) {
        case 401:
          // 去登录页
          message = '未授权，请登录'
          break
        case 403:
          message = '无权访问'
          break
        case 404:
          message = '请求地址错误'
          break
        case 500:
          message = '服务器出现错误'
          break
        case 501:
          message = '服务未实现'
          break
        case 502:
          message = '网关错误'
          break
        case 503:
          message = '服务不可用'
          break
        case 504:
          message = '网关超时'
          break
        case 505:
          message = 'HTTP版本不受支持'
          break
        default:
          message = '网络问题'
          break
      }
      ElMessage({
        type: 'error',
        message,
        duration: 3 * 1000
      })
    }
    return Promise.reject(err)
  }
)

export default request